package com.hmall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;

    @Autowired
    private JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //0 获取请求与响应对象
        ServerHttpRequest request = exchange.getRequest();
        //  获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //1. 获取请求路径
        String path = request.getURI().getPath();
        log.info("请求路径：{}", path);
        //2. 判断是否是白名单，是则放行, 谁跟谁对比: 请求路径跟白名单对象
        List<String> excludePaths = authProperties.getExcludePaths();
        if(excludePaths.contains(path)){
            // 放行
            return chain.filter(exchange);
        }
        //3. 获取请求头中的token
        String token = request.getHeaders().getFirst("Authorization");
        //4. 解析token
        if(StrUtil.isNotEmpty(token)){
            try {
                // 登录用户id
                Long userId = jwtTool.parseToken(token);
                //5. 把用户id存入请求头 mutate转换，转变，改变
                request.mutate().header("user-info",String.valueOf(userId));
                // 放行
                return chain.filter(exchange);
            } catch (Exception e) {
                log.error("解析token失败", e);
            }
        }

        //返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
